using System;
using System.Collections;
using System.IO;
using System.IO.Ports;
using System.Runtime.Serialization;
using System.Text;

namespace ReadDataFromSerial {
    public class ReadDataFromSerial {
        // 测量体表电阻
        // TODO 设置串口
        private static readonly string _sensorPortName =
            "XXXXX";

        private static readonly int _sensorBaudRate = 9600;

        // 文件名
        private static readonly string _fileName =
            "../../../data/sensorData.txt";
        
        static void Main(string[] args) {
            SerialPort sensorSerialPort =
                new SerialPort(_sensorPortName, _sensorBaudRate);
            sensorSerialPort.Open();
            try {
                FileStream fileStream =
                    new FileStream(_fileName, FileMode.Append);
                StreamWriter streamWriter = new StreamWriter(fileStream);
                while (sensorSerialPort.ReadLine() != "") {
                    DateTime dateTime = DateTime.Now;
                    string lineToWrite = dateTime + "," +
                        sensorSerialPort.ReadLine();
                    Console.Write(lineToWrite);
                    streamWriter.Write(lineToWrite);
                    streamWriter.Flush();
                }
                streamWriter.Close();
                fileStream.Close();
            } catch (Exception e) {
                Console.WriteLine(e);
            }
        }
    }
}